﻿using Newtonsoft.Json;
using RabbitMQ.Client;
using System.Text;
using YDT_WebSites.Models;

namespace YDT_WebSites.Services
{
    /// <summary>
    /// 消息发送
    /// </summary>
    public class MessagePublish
    {
        public IModel channel;
        public IConfiguration configuration;

        public MessagePublish(IConfiguration configuration)
        {
            // 1、建立RabbitMQ连接
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.HostName = configuration["RabbitMQ:HostName"];
            connectionFactory.Port = int.Parse(configuration["RabbitMQ:Port"]);
            connectionFactory.UserName = configuration["RabbitMQ:UserName"];
            connectionFactory.Password = configuration["RabbitMQ:Password"];
            connectionFactory.VirtualHost = configuration["RabbitMQ:VirtualHost"];
            IConnection connection = connectionFactory.CreateConnection();

            // 2、创建连接通道
             channel = connection.CreateModel();
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        public void PublishMessage<T>(string QueueName,T t)
        {
            //发送商品数据。
            
            // 3、发送商品数据
            // 3.1、创建队列
            channel.QueueDeclare(QueueName, false, false, false);

            // 3.2、商品转换
            string productJson = JsonConvert.SerializeObject(t);
            byte[] productByte = Encoding.UTF8.GetBytes(productJson);

            // 3.2、发送数据
            channel.BasicPublish("",
                                QueueName,
                                 true,
                                 channel.CreateBasicProperties(),
                                  productByte);
        }
    }
}
